package com.atguigu.srb.service.sms.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.srb.base.consts.SrbMqConst;
import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.service.sms.service.SmsService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

//mq消费者
@Component
public class MqListener {
    @Resource
    SmsService smsService;
    //使用已有的队列 进行消费
    @RabbitListener(queues = {SrbMqConst.SMS_QUEUE}) //消费SMS队列中的消息
    public void smsSendListener(Message message , Channel channel, SmsDTO smsDto) throws IOException {
        try {
//            SmsDTO smsDTO = JSON.parseObject(smsDto, SmsDTO.class);
            //发送短信业务
            smsService.mqSendMsg(smsDto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            if(message.getMessageProperties().isRedelivered()){
                //如果消息是重新投递 再次消费失败 丢弃消息到绑定的死信队列中
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                        false,true);
            }

        }

    }

}
